/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bgu.ppm.sim.impl.mas.agents;

import bgu.ppm.sim.api.mas.Agent;
import bgu.ppm.sim.api.mas.Model;
import java.awt.Image;

/**
 *
 * @author User
 */
public abstract class AbstractAgent<T extends Model> implements Agent<T> {

    private int id = Integer.MIN_VALUE;
    private State state = State.UNINITIALIZED;
    private T model;

    @Override
    public int getId() {
        return id;
    }

    @Override
    public void setId(int id) {
        if (this.id == Integer.MIN_VALUE) {
            this.id = id;
        } else {
            panic("attempt to change id after it was set detected, bad user!");
        }
    }

    protected T getModel() {
        return model;
    }

    protected boolean isFirstAgent() {
        return getId() == 0;
    }
    
    protected boolean isLastAgent() {
        return getId() == model.getNumberOfAgents() - 1;
    }    

    @Override
    public void initialize(T model) {
        this.model = model;
        _initialize(model);
        state = State.INITIALIZED;
    }

    protected abstract void start();

    @Override
    public Image getIcon() {
        return null;
    }

    @Override
    public String getVisualName() {
        return "Agent " + id;
    }

    @Override
    public String getDescription() {
        return "Agent: " + getClass().getSimpleName();
    }

    @Override
    public void tick() {
        state = State.RUNNING;
        try {
            _tick();
        } catch (Exception ex) {
            panic(ex);
        }
    }

    @Override
    public State getState() {
        return state;
    }

    protected void terminate() {
        state = State.TERMINATED;
    }

    protected void panic(String msg) {
        state = State.CRUSHED;
        throw new PanickedAgentException(msg);
    }

    protected void panic(Exception ex) {
        state = State.CRUSHED;
        throw new PanickedAgentException(ex);
    }

    protected abstract void _initialize(T model);

    protected abstract void _tick();
}
